import * as VueRouter from "vue-router"
import { getToken } from "@/utils/jsCookie";
import { clearPending } from "@/utils/requestCancel";

import store from "@/store"
import screen from "@/views/screen"
const router = VueRouter.createRouter({
    history: VueRouter.createWebHashHistory(),
    routes: [
      {
        path: '/',
        redirect: '/screen',
        component: screen,
      },
      {
        path: '/login',
        component: ()=> import('@/views/login'),
        meta: { title: '登录' }
      },
      {
        path: '/screen',
        component: ()=> import('@/views/screen'),
        meta: { title: '大屏' }
      },
    ]
  })
  router.beforeEach(async (to, from, next)=> {
    clearPending();
    const token = getToken();
    if(token) {
        const userInfo = store.state.user.userInfo;
        if(userInfo) {
            if(to.path === '/login') {
                next({ path: '/' })
            } else {
                const asyncRoutes = store.state.user.asyncRoutes;
                if(asyncRoutes.length > 0) {
    
                    console.log('------> ',router.getRoutes())
                    
                    next();
                } else {
                    await store.dispatch("user/findUserMenu")
                    next({ ...to, replace: true })
                }
            }
        } else {
            try {
                await store.dispatch("user/getLoginInfo")
                next({ ...to, replace: true })
            } catch (e) {
                next(`/login?redirect=${ to.fullPath }`)
                
                console.log(e)
            }
            
        }
        
    } else {
        if (to.path === '/login') {
            next();
        } else {
            next(`/login?redirect=${ to.fullPath }`)
            // `/login?redirect=${ to.fullPath }`
        }
    }
    
})


export default router;